import React, {Component} from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  StatusBar,
  SafeAreaView
} from 'react-native';

// 验证码输入框
import {CodeField} from 'react-native-confirmation-code-field';

// 第三方待图标的input标签
import {Input} from 'react-native-elements';

import {pxToDp} from "../../../utils/styleKits.js";
import validator from "../../../utils/validator.js";
import request from "../../../utils/request.js";
import {ACCOUNT_LOGIN} from '../../../utils/pathMap.js'
import Toast from "../../../utils/Toast.js";
import ThButton from "../../../components/THButton.js";

import {inject, observer} from 'mobx-react'

@inject('RootStore')
@observer
export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      phone: '13266858126',   // 用户输入的手机号码
      defaultValidataCode: '123456',   // 默认验证码
      showErrorMsg: false,   // 是否显示错误提示信息
      inputValidateCode: '',  // 用户输入的验证码
      btnText: '重新获取',   //输入验证码组件中btn按钮文字
      isDisabled: false,  //是否禁用按钮

      showInputPhone: true,  // 显示输入手机号码组件
      showInputValidateCode: false,  // 显示输入验证码组件
    }
  }

  render() {
    let {showInputPhone, showInputValidateCode} = this.state;
    return (
      <View style={styles.container}>
        {/* 状态栏 */}
        <StatusBar translucent={true} backgroundColor='transparent'/>

        {/* 安全区域 */}
        <SafeAreaView style={{flex: 1}}>
          {/* 顶部图片 */}
          <Image style={styles.img} source={require('../../../images/profileBackground.jpg')}/>

          {/* 显示输入手机号组件 */}
          {showInputPhone ? this.showInputPhone() : null}

          {/* 显示输入验证码组件 */}
          {showInputValidateCode ? this.showInputValidateCode() : null}

        </SafeAreaView>
      </View>
    );
  }

  // 显示输入验证码组件
  showInputValidateCode = () => {
    let {phone, inputValidateCode, btnText,isDisabled} = this.state;

    return <View>
      <Text style={styles.phoneTxt}>输入6位验证码</Text>
      <Text style={styles.hasSendText}>已发送到: +86 {phone}</Text>
      <CodeField
        value={inputValidateCode}
        onChangeText={this.changeValidateText}
        cellCount={6}
        rootStyle={styles.codeFieldRoot}
        keyboardType="number-pad"
        textContentType="oneTimeCode"
        renderCell={this._renderCell}
      />

      {/* 按钮 */}
      <ThButton
        disabled={isDisabled}
        style={{
          width: '85%', alignSelf: 'center', height: pxToDp(50),
          marginTop: pxToDp(50), borderRadius: pxToDp(25), overflow: 'hidden'
        }}
        textStyle={{fontSize: pxToDp(16)}}
        onPress={this.countDown}
      >
        {btnText}
      </ThButton>
    </View>
  };

  // 输入验证码，并验证验证码
  changeValidateText = (value) => {
    let {phone} = this.state;
    this.setState({
      inputValidateCode: value
    },()=>{
      let {inputValidateCode,defaultValidataCode} = this.state;
      if (inputValidateCode.length === 6 && inputValidateCode === defaultValidataCode){
        this.props.RootStore.setUserInfo(phone, '123456','123123');

        // this.props.navigation.push("userInfo");
        this.props.navigation.reset({
          routes:[{name:'tabBar'}]
        })
      } else if (inputValidateCode.length === 6 && inputValidateCode !== defaultValidataCode){
        Toast.show({
          text: '验证码输入错误',
          position: "center",
          duration: 2000,
        })
      }
    });
  };


  // 开始倒计时
  countDown = () => {
    let second = 5;

    // 禁用按钮
    this.setState({
      isDisabled: true
    });

    let timeId = setInterval(() => {
      if (second < 0) {
        this.setState({
          btnText: '重新获取',
          isDisabled: false,
        },()=>{
          clearInterval(timeId);
        });
      } else {
        this.setState({
          btnText: '重新获取(' + second + ')s',
        })
      }
      second--;
    }, 1000)
  };

  // 输入验证码组件每一个小框
  _renderCell = ({index, symbol}) => {
    return <Text key={index} style={styles.cell}>
      {symbol}
    </Text>
  };

  // 显示输入手机号码组件
  showInputPhone = () => {
    let {showErrorMsg, phone} = this.state;

    return <View>
      <Text style={styles.phoneTxt}>手机号登录注册</Text>
      {/* 输入手机号码 */}

      <Input
        placeholder={'请输入手机号码'}
        value={phone}
        maxLength={11}
        keyboardType={'phone-pad'}
        leftIcon={{type: 'font-awesome', name: 'phone', color: '#999'}}
        errorMessage={showErrorMsg ? '手机号码格式不正确' : ''}
        onChangeText={this.getPhone}
      />

      {/* 按钮 */}
      <ThButton
        style={{
          width: '85%', alignSelf: 'center', height: pxToDp(50),
          marginTop: pxToDp(50), borderRadius: pxToDp(25), overflow: 'hidden'
        }}
        textStyle={{fontSize: pxToDp(16)}}
        onPress={this.getValidateCode}
      >
        获取验证码
      </ThButton>
    </View>
  };

  // 获取用户输入的手机号
  getPhone = (value) => {
    this.setState({
      phone: value
    })
  };

  // 获取验证码
  getValidateCode = async () => {
    let {phone} = this.state;

    if (validator.validatePhone(phone)) {
      // 手机号码正则验证通过
      this.setState({
        showErrorMsg: false
      })
    } else {
      // 手机号码正则验证未通过
      this.setState({
        showErrorMsg: true,
      });
      return false
    }

    this.setState({
      showInputPhone: false,  // 显示输入手机号码组件
      showInputValidateCode: true,  // 显示输入验证码组件
    });
    this.countDown()

    // let res = await request.post(ACCOUNT_LOGIN, {
    //   tel: phone,
    // });
    //
    // if (res.message === '手机已经被注册') {
    //   this.setState({
    //     showInputPhone: false,  // 显示输入手机号码组件
    //     showInputValidateCode: true,  // 显示输入验证码组件
    //   });
    //   this.countDown()
    // }
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  img: {
    width: '100%',
    height: pxToDp(200),
  },
  phoneTxt: {
    margin: pxToDp(20),
    marginBottom: pxToDp(5),
    fontSize: pxToDp(20),
    fontWeight: 'bold',
  },
  hasSendText: {
    marginLeft: pxToDp(20),
    marginRight: pxToDp(20),
    fontSize: pxToDp(12),
  },
  codeFieldRoot: {
    margin: pxToDp(20),
    marginBottom: 0,
  },
  cell: {
    width: pxToDp(40),
    height: pxToDp(40),
    fontSize: pxToDp(24),
    textAlign: 'center',
    borderBottomWidth: 1,
    borderColor: '#00000030',
  },

});
